import React, { useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { Card, Flex, message, Upload, Button, Form } from "antd";
import type { GetProp, UploadProps } from "antd";
import IconSvg from "@/components/IconSvg";
import FormWarpper from "@/components/FormWarpper";
import { delViewTag } from "@/utils/common";

type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];

const getBase64 = (img: FileType, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
};
import ImgCrop from "antd-img-crop";
import "./index.less";

export const Profile = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const [info, setInfo] = useState([
    { icon: "user", name: "用户名称", text: "" },
    { icon: "user", name: "手机号码", text: "" },
    { icon: "user", name: "用户邮箱", text: "" },
    { icon: "user", name: "所属部门", text: "" },
    { icon: "user", name: "岗位信息", text: "" },
    { icon: "user", name: "所属角色", text: "" },
    { icon: "user", name: "创建日期", text: "" },
  ]);
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const beforeUpload = (file: FileType) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps["onChange"] = (info) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as FileType, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>点击上传头像</div>
    </button>
  );

  const tabList = [
    {
      key: "basicInfo",
      tab: "基本资料",
    },
    {
      key: "passWord",
      tab: "修改密码",
    },
  ];

  const formBasicSetting = {
    span: 24,
    menuPosition: "left",
    columns: [
      {
        name: "username",
        label: "用户昵称",
        placeholder: "请输入用户昵称",
        allowClear: true,
        rules: [{ required: true, message: "请输入用户昵称!" }],
      },
      {
        name: "userPhone",
        label: "手机号码",
        placeholder: "请输入手机号码",
        allowClear: true,
        rules: [
          { required: true, message: "请输入手机号码!" },
          {
            pattern: /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/,
            message: "手机号码格式不正确!",
          },
        ],
      },
      {
        name: "userEmail",
        label: "邮箱",
        placeholder: "请输入邮箱",
        allowClear: true,
        rules: [
          { required: true, message: "请输入邮箱!" },
          {
            pattern:
              /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
            message: "邮箱格式不正确!",
          },
        ],
      },
      {
        name: "sex",
        label: "性别",
        formType: "radio",
        dicData: [
          { value: "1", label: "男" },
          { value: "0", label: "女" },
        ],
      },
    ],
  };

  const formBasicMenuSlot = (
    <span style={{ marginLeft: "100px" }}>
      <Button type="primary" htmlType="submit">
        保存
      </Button>
      <Button
        type="primary"
        danger
        style={{ marginLeft: "20px" }}
        htmlType="button"
        onClick={(e) => handleClose()}
      >
        关闭
      </Button>
    </span>
  );

  const createFinish = (values) => {
    console.log("values", values);
  };

  const formPassWordSetting = {
    span: 24,
    menuPosition: "left",
    columns: [
      {
        name: "oldPassWord",
        label: "旧密码",
        placeholder: "请输入旧密码",
        allowClear: true,
        rules: [
          { required: true, message: "请输入旧密码!" },
          {
            pattern:
              /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{6,20}$/,
            message: "旧密码格式不正确!",
          },
        ],
      },
      {
        name: "newPassWord",
        label: "新密码",
        placeholder: "请输入新密码",
        allowClear: true,
        rules: [
          { required: true, message: "请输入新密码!" },
          {
            pattern:
              /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{6,20}$/,
            message: "新密码格式不正确!",
          },
        ],
      },
      {
        name: "surePassWord",
        label: "确认密码",
        placeholder: "请再次输入密码",
        allowClear: true,
        rules: [
          { required: true, message: "请再次输入密码!" },
          {
            validator: (rule, value, callback) => {
              // console.log(value, 'value')
              // console.log(form.getFieldsValue().newPassWord, 'form')
              if (value && value !== form.getFieldsValue().newPassWord) {
                callback("两次输入密码不一致！");
              } else {
                callback();
              }
            },
          },
        ],
      },
    ],
  };

  const formPassWordMenuSlot = (
    <span style={{ marginLeft: "100px" }}>
      <Button type="primary" htmlType="submit">
        保存
      </Button>
      <Button
        type="primary"
        danger
        style={{ marginLeft: "20px" }}
        htmlType="button"
        onClick={(e) => handleClose()}
      >
        关闭
      </Button>
    </span>
  );

  const passWordFinish = (values) => {
    console.log("values", values);
  };

  const handleClose = () => {
    delViewTag(location.pathname);
    navigate("/");
  };

  const contentList: Record<string, React.ReactNode> = {
    basicInfo: (
      <FormWarpper
        formSetting={formBasicSetting}
        formMenuSlot={formBasicMenuSlot}
        handleFinish={createFinish}
        form={form}
      />
    ),
    passWord: (
      <div>
        <div className="tips">
          <p>密码长度由6-20位数字，大小写字母，特殊字符组成</p>
        </div>
        <FormWarpper
          formSetting={formPassWordSetting}
          formMenuSlot={formPassWordMenuSlot}
          handleFinish={passWordFinish}
          form={form}
        />
      </div>
    ),
  };

  const [activeTabKey, setActiveTabKey] = useState<string>("basicInfo");
  const onTab1Change = (key: string) => {
    setActiveTabKey(key);
  };

  return (
    <div className="user-profile pageWarpper">
      <div className="user-profile-left">
        <Card title="个人信息">
          <ImgCrop rotationSlider>
            <Upload
              name="avatar"
              listType="picture-circle"
              className="avatar-uploader"
              showUploadList={false}
              action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </ImgCrop>
          {info.map((item, index) => (
            <p className="info-item" key={index}>
              <IconSvg name={item.icon} />
              <span style={{ margin: "0 6px" }}>{item.name}</span>
              <span>{item.text}</span>
            </p>
          ))}
        </Card>
      </div>
      <div className="user-profile-right">
        <Card
          title="基本资料"
          tabList={tabList}
          activeTabKey={activeTabKey}
          onTabChange={onTab1Change}
        >
          {contentList[activeTabKey]}
        </Card>
      </div>
    </div>
  );
};

export default Profile;
